package com.helen.ui.product;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.ColorDrawable;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.NestedScrollView;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.helen.adapter.SingleImgAdapter;
import com.helen.db.UserHelper;
import com.helen.entity.CommitProductEntity;
import com.helen.entity.ProductDetailEntity;
import com.helen.entity.ProductSpecEntity;
import com.helen.entity.SelectSpecEntity;
import com.helen.event.InfoEnent;
import com.helen.global.Constants;
import com.helen.shopping.R;
import com.helen.ui.BaseActivity;
import com.helen.ui.MainActivity;
import com.helen.ui.order.AllCommentActivity;
import com.helen.ui.order.CommitOrderActivity;
import com.helen.utils.GlideImageLoader;
import com.helen.utils.ImageLoadUtil;
import com.helen.utils.JsonUtil;
import com.helen.utils.MyLog;
import com.helen.utils.PhoneUtils;
import com.helen.utils.StatusBarUtil;
import com.helen.utils.tiputils.MToast;
import com.helen.widget.TagsLayout;
import com.youth.banner.Banner;
import com.zhouyou.http.EasyHttp;
import com.zhouyou.http.cache.converter.SerializableDiskConverter;
import com.zhouyou.http.cache.model.CacheMode;
import com.zhouyou.http.cache.model.CacheResult;
import com.zhouyou.http.callback.SimpleCallBack;
import com.zhouyou.http.exception.ApiException;
import com.zhouyou.http.model.HttpParams;

import org.greenrobot.eventbus.EventBus;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;

/**
 * Created by yang on 2018/5/15.
 */

public class ProductDetailActivity extends BaseActivity implements SwipeRefreshLayout.OnRefreshListener {
    Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case REFRESH:
                    productDetailApi();
                    productSpecApi();
                    mSwipeLayout.setRefreshing(false);
                    break;

            }
            return false;
        }


    });
    private static final int REFRESH = 0X110;
    @BindView(R.id.nestedScrollView)
    NestedScrollView mNestedScrollView;
    @BindView(R.id.ll_top)
    LinearLayout llTop;
    @BindView(R.id.rel_top_normal)
    RelativeLayout relTopNormal;
    @BindView(R.id.swipe_refresh)
    SwipeRefreshLayout mSwipeLayout;
    @BindView(R.id.banner)
    Banner banner;
    @BindView(R.id.tv_product_name)
    TextView tvProductName;
    @BindView(R.id.tv_product_now_price)
    TextView tvProductNowPrice;
    @BindView(R.id.tv_product_old_price)
    TextView tvProductOldPrice;
    @BindView(R.id.tv_expressprice)
    TextView tvExpressprice;
    @BindView(R.id.tv_paycount)
    TextView tvPaycount;
    @BindView(R.id.tv_count)
    TextView tvCount;
    @BindView(R.id.tv_good_spec)
    TextView tvGoodSpec;
    @BindView(R.id.ll_good_spec)
    LinearLayout llGoodSpec;
    @BindView(R.id.tv_comment_count)
    TextView tvCommentCount;
    @BindView(R.id.tv_all_comment)
    TextView tvAllComment;
    @BindView(R.id.img_user)
    CircleImageView imgUser;
    @BindView(R.id.tv_comment_name)
    TextView tvCommentName;
    @BindView(R.id.tv_comment_content)
    TextView tvCommentContent;
    @BindView(R.id.rv_comment_img)
    RecyclerView rvCommentImg;
    @BindView(R.id.rv_product_img)
    RecyclerView rvProductImg;
    @BindView(R.id.tv_add_car)
    TextView tvAddCar;
    @BindView(R.id.tv_buy)
    TextView tvBuy;
    private int productId;
    private ProductDetailEntity productDetailEntity;
    private List<String> bannerList = new ArrayList<>();
    private SingleImgAdapter commentImgAdapter;
    private List<String> commentImgList = new ArrayList<>();
    private SingleImgAdapter productImgAdapter;
    private List<String> productImgList = new ArrayList<>();
    private PopupWindow popWnd;
    private ArrayList<TextView> tvTabs = new ArrayList<>();
    private List<ProductSpecEntity> productSpecEntityList = new ArrayList<>();
    private List<ProductSpecEntity.ValueBean> selectSpecValueListBean = new ArrayList<>();
    private SelectSpecEntity selectSpecEntity = new SelectSpecEntity();
    private String spec = "";//提交订单商品规格字段

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_product_detail;
    }

    @Override
    protected void initInjector() {

    }

    @Override
    protected void initViews() {
        StatusBarUtil.setTranslucentForImageViewInFragment(ProductDetailActivity.this, null);
        setTopView();
        mSwipeLayout.setOnRefreshListener(this);
        productId = getIntent().getIntExtra("productId", 0);

        commentImgAdapter = new SingleImgAdapter(R.layout.item_comment_img_recycler, commentImgList);
        rvCommentImg.setLayoutManager(new GridLayoutManager(ProductDetailActivity.this, 4));
        rvCommentImg.setAdapter(commentImgAdapter);

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(ProductDetailActivity.this) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        };
        productImgAdapter = new SingleImgAdapter(R.layout.item_product_detail_img_recycler, productImgList);
        rvProductImg.setLayoutManager(linearLayoutManager);
        rvProductImg.setAdapter(productImgAdapter);

        productDetailApi();
        productSpecApi();
    }

    @Override
    protected void updateViews() {

    }

    private void setTopView() {
        final int height = llTop.getLayoutParams().height;
        MyLog.e("yang", "height==" + height);
        mNestedScrollView.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
            // 将透明度声明成局部变量用于判断
            int alpha = 0;
            float scale = 0;

            @Override
            public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                MyLog.e("yang", "scrollY==" + scrollY);
                if (scrollY <= height) {
                    scale = (float) scrollY / height;
                    alpha = (int) (255 * scale);
                    // 随着滑动距离改变透明度
                    llTop.setBackgroundColor(Color.argb(alpha, 0xFF, 0x7A, 0x00));

                } else {
                    if (alpha < 255) {
                        // 防止频繁重复设置相同的值影响性能
                        alpha = 255;
                        llTop.setBackgroundColor(Color.argb(alpha, 0xFF, 0x7A, 0x00));

                    }
                }
                if (scrollY == 0) {
                    llTop.setVisibility(View.GONE);
                    relTopNormal.setVisibility(View.VISIBLE);
                }

                if (scrollY > 0) {
                    llTop.setVisibility(View.VISIBLE);
                    relTopNormal.setVisibility(View.GONE);
                }
            }

        });
    }

    @Override
    public void onRefresh() {
        mHandler.sendEmptyMessageDelayed(REFRESH, 1500);
    }

    //    详情接口
    private void productDetailApi() {
//        mMProgressDialog.show();
        HttpParams params = new HttpParams();
        params.put("iid", productId + "");
        EasyHttp.post(Constants.API_JSONAPI_PRODUCTDETAIL)
                .cacheMode(CacheMode.CACHEANDREMOTEDISTINCT)
                .cacheKey(Constants.API_JSONAPI_PRODUCTDETAIL + "_" + productId)
                .cacheDiskConverter(new SerializableDiskConverter())
                .params(params)
                .execute(new SimpleCallBack<CacheResult<String>>() {
                    @Override
                    public void onCompleted() {
                        super.onCompleted();
//                        mMProgressDialog.dismiss();
                    }

                    @Override
                    public void onError(ApiException e) {
                        MyLog.d(TAG, "获取商品详情失败==" + e.toString());
                        MToast.makeTextShort(ProductDetailActivity.this, getString(R.string.service_error)).show();
                    }

                    @Override
                    public void onSuccess(CacheResult<String> stringCacheResult) {
                        MyLog.e("yang", "商品详情==" + stringCacheResult.data);
                        int code = JsonUtil.getJsonValuesInt(stringCacheResult.data, "code");
                        String msg = JsonUtil.getJsonValuesString(stringCacheResult.data, "msg");
                        if (code == 0) {
                            Gson gson = new GsonBuilder().create();
                            productDetailEntity = gson.fromJson(stringCacheResult.data, ProductDetailEntity.class);

                            bannerList.clear();
                            for (int i = 0; i < productDetailEntity.getImgs().size(); i++) {
                                bannerList.add(productDetailEntity.getImgs().get(i).getUrl());
                            }
                            if (bannerList != null && bannerList.size() > 0) {
                                initBanner();
                            }
                            tvProductName.setText(productDetailEntity.getName());
                            if (productDetailEntity.getDiscountprice() != 0) {
                                tvProductNowPrice.setText("￥" + productDetailEntity.getDiscountprice());
                                tvProductOldPrice.setText("￥" + productDetailEntity.getCostprice());
                                tvProductOldPrice.setVisibility(View.VISIBLE);
                                tvProductOldPrice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG);  // 设置中划线并加清晰
                            } else {
                                tvProductNowPrice.setText("￥" + productDetailEntity.getCostprice());
                                tvProductOldPrice.setVisibility(View.GONE);
                            }


                            if (productDetailEntity.getExpressprice() == 0) {
                                tvExpressprice.setText("快递: 免运费");
                            } else {
                                tvExpressprice.setText("快递: " + productDetailEntity.getExpressprice());
                            }

                            tvPaycount.setText("月销" + productDetailEntity.getPaycount() + "笔");

                            if (productDetailEntity.getCount() != -1) {
                                tvCount.setText("库存" + productDetailEntity.getCount() + productDetailEntity.getUnit());
                            } else {
                                tvCount.setText("库存9999+");
                            }

                            tvCommentCount.setText("商品评价" + productDetailEntity.getCommentcount());
                            ImageLoadUtil.displayImage(ProductDetailActivity.this, imgUser, productDetailEntity.getCommentuserimg(), R.mipmap.icon_person_head, R.mipmap.icon_person_head);
                            tvCommentName.setText(productDetailEntity.getCommentname());
                            tvCommentContent.setText(productDetailEntity.getCommentcontent());



                            //评论图片展示
                            if (!TextUtils.isEmpty(productDetailEntity.getCommentimgs())) {
                                commentImgList.clear();
                                commentImgList = Arrays.asList(productDetailEntity.getCommentimgs().split(","));
                                commentImgAdapter.setNewData(commentImgList);
                            }
                            //详情图片

                            if (productDetailEntity.getDetailimgs() != null && productDetailEntity.getDetailimgs().size() > 0) {
                                productImgList.clear();
                                for (int i = 0; i < productDetailEntity.getDetailimgs().size(); i++) {
                                    productImgList.add(productDetailEntity.getDetailimgs().get(i).getUrl());
                                }
                                productImgAdapter.setNewData(productImgList);
                                MyLog.e("yang", "productImgList.size==" +   productImgAdapter.getData().size());
                            }


                        } else {
                            MToast.makeTextShort(ProductDetailActivity.this, msg).show();
                        }
                    }
                });
    }


    //获取商品规格
    private void productSpecApi() {
        mMProgressDialog.show();
        HttpParams params = new HttpParams();
        params.put("iid", productId + "");
        EasyHttp.post(Constants.API_JSONAPI_PRODUCTSPEC)
                .params(params)
                .execute(new SimpleCallBack<String>() {
                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                        mMProgressDialog.dismiss();
                    }

                    @Override
                    public void onError(ApiException e) {
                        MyLog.d(TAG, "获取商品规格失败==" + e.toString());
                        MToast.makeTextShort(ProductDetailActivity.this, getString(R.string.service_error)).show();
                    }

                    @Override
                    public void onSuccess(String result) {
                        MyLog.e("yang", "获取商品规格==" + result);
                        String data = PhoneUtils.checkResponseFlag2(ProductDetailActivity.this, result, TAG);
                        if (data != null && !data.equals("[]")) {
                            productSpecEntityList.clear();
                            selectSpecValueListBean.clear();
                            productSpecEntityList = new Gson().fromJson(data, new TypeToken<List<ProductSpecEntity>>() {
                            }.getType());
                            for (int i = 0; i < productSpecEntityList.size(); i++) {
                                for (int j = 0; j < productSpecEntityList.get(i).getValue().size(); j++) {
                                    productSpecEntityList.get(i).setMyId(i);
                                    productSpecEntityList.get(i).getValue().get(j).setMyId(i);
                                }

                            }


                        }

                    }
                });
    }

    private void initBanner() {
        banner.setImages(bannerList)
                .setImageLoader(new GlideImageLoader())
//                .setBannerAnimation(CubeOutTransformer.class)
                .start();
    }

    @OnClick({R.id.img_back, R.id.img_back_normal, R.id.ll_good_spec, R.id.tv_all_comment, R.id.tv_add_car, R.id.tv_buy})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.img_back:
                myBack();
                break;
            case R.id.img_back_normal:
                myBack();
                break;
            case R.id.ll_good_spec:
                break;
            case R.id.tv_all_comment:
                Intent ti = new Intent(ProductDetailActivity.this, AllCommentActivity.class);
                ti.putExtra("iid", productId);
                startActivity(ti);
                break;
            case R.id.tv_add_car:
                if (checkLoginState()) {
                    showGoodsStandard(view, true);
                }
                break;
            case R.id.tv_buy:
                if (checkLoginState()) {
                    showGoodsStandard(view, false);
                }

                break;
        }
    }

    private void showGoodsStandard(View v, final boolean isAddShoppingCar) {
        tvTabs.clear();
        selectSpecValueListBean.clear();
        View contentView = LayoutInflater.from(ProductDetailActivity.this).inflate(R.layout.pop_goods_standard, null);
        popWnd = new PopupWindow(contentView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        contentView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (popWnd != null && popWnd.isShowing()) {
                    popWnd.dismiss();
                }
                return false;
            }
        });
        ColorDrawable cd = new ColorDrawable(0x77000000);
        popWnd.setBackgroundDrawable(cd);
        // 设置点击窗口外边窗口消失
        popWnd.setOutsideTouchable(true);
        // 设置此参数获得焦点，否则无法点击
        popWnd.setFocusable(true);
        popWnd.setAnimationStyle(R.style.ShoppingCartPopupAnimation);
//        popWnd.setClippingEnabled(false);
        LinearLayout llContainer = (LinearLayout) contentView.findViewById(R.id.ll_container);
        final TextView tvSure = (TextView) contentView.findViewById(R.id.tv_sure);
        final TextView tvPopChooseSpec = (TextView) contentView.findViewById(R.id.tv_pop_choose_spec);
        final TextView tvGoodsPrice = (TextView) contentView.findViewById(R.id.tv_goods_price);
        final ImageView ivPopGoodsDetail = (ImageView) contentView.findViewById(R.id.iv_pop_goods_detail);
        final TextView tvKuCun = (TextView) contentView.findViewById(R.id.tv_kucun);
        ImageView ivGoodsMinus = (ImageView) contentView.findViewById(R.id.iv_goods_minus);
        final TextView tvGoodsCount = (TextView) contentView.findViewById(R.id.tv_goods_count);
        ImageView ivGoodsAdd = (ImageView) contentView.findViewById(R.id.iv_goods_add);

        if (productDetailEntity.getImgs() != null && productDetailEntity.getImgs().size() > 0) {
            ImageLoadUtil.displayImage(ProductDetailActivity.this, ivPopGoodsDetail, productDetailEntity.getImgs().get(0).getUrl(), R.mipmap.app_logo, R.mipmap.app_logo);
        }


        if (productSpecEntityList != null && productSpecEntityList.size() > 0) {
            for (int i = 0; i < productSpecEntityList.size(); i++) {
                View addView = LayoutInflater.from(ProductDetailActivity.this).inflate(R.layout.include_goods_standard, null);
                TagsLayout tagsClassify = (TagsLayout) addView.findViewById(R.id.tags_classify);
                TextView tvClassifyName = (TextView) addView.findViewById(R.id.tv_classify_name);
                ViewGroup.MarginLayoutParams lp = new ViewGroup.MarginLayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                tvClassifyName.setText(productSpecEntityList.get(i).getName());

                for (int j = 0; j < productSpecEntityList.get(i).getValue().size(); j++) {
                    View tagView = View.inflate(ProductDetailActivity.this, R.layout.item_screen_brand, null);
                    TextView textView = (TextView) tagView.findViewById(R.id.tv_screen_item);
                    ProductSpecEntity.ValueBean tag = productSpecEntityList.get(i).getValue().get(j);
                    textView.setText(tag.getVal());
                    textView.setTag(tag);
                    tvTabs.add(textView);
                    tagView.setTag(false);
                    tagView.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            TextView tv = (TextView) v.findViewById(R.id.tv_screen_item);
                            updateSelectTabs(tv, tvGoodsPrice, tvPopChooseSpec, ivPopGoodsDetail,tvKuCun);
                        }
                    });
                    tagsClassify.addView(tagView, lp);
                }
                llContainer.addView(addView);

            }
        } else {
            if (productDetailEntity.getDiscountprice() != 0) {
                tvGoodsPrice.setText("￥" + (productDetailEntity.getDiscountprice()));
            } else {
                tvGoodsPrice.setText("￥" + productDetailEntity.getCostprice());
            }
            spec = "";
            tvPopChooseSpec.setText(spec);

        }
        popWnd.showAtLocation(v, Gravity.BOTTOM, 0, 0);

        ivGoodsMinus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int myCount = Integer.valueOf(tvGoodsCount.getText().toString());
                if (myCount > 1) {
                    myCount = myCount - 1;
                    tvGoodsCount.setText("" + myCount);
                }


            }
        });
        ivGoodsAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int myCount = Integer.valueOf(tvGoodsCount.getText().toString());
                myCount = myCount + 1;
                tvGoodsCount.setText("" + myCount);
            }
        });

        tvSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                if (selectSpecEntity != null && selectSpecEntity.getId() != 0 ) {
                if (productDetailEntity.getIsSpec() == 1) {
                    if (isAddShoppingCar) {
                        setCarApi(selectSpecEntity.getId() + "", tvGoodsCount.getText().toString());
                    } else {
                        MyLog.e("yang", "有规格立即购买");
                        if (selectSpecEntity != null && selectSpecEntity.getId() != 0) {
                            Intent ti = new Intent(ProductDetailActivity.this, CommitOrderActivity.class);
                            ti.putExtra("commitProductEntityList", (Serializable) selectProductList(tvGoodsCount));
                            ti.putExtra("isShopCar", false);
                            startActivity(ti);
                            popWnd.dismiss();
                        } else {
                            MToast.makeTextLong(ProductDetailActivity.this, "请选择规格").show();
                        }


                    }
                } else {
                    if (isAddShoppingCar) {
                        setCarApi("", tvGoodsCount.getText().toString());
                    } else {
                        MyLog.e("yang", "无规格立即购买");
                        Intent ti = new Intent(ProductDetailActivity.this, CommitOrderActivity.class);
                        ti.putExtra("commitProductEntityList", (Serializable) selectProductList(tvGoodsCount));
                        ti.putExtra("isShopCar", false);
                        startActivity(ti);
                        popWnd.dismiss();
                    }

                }

            }
        });
    }


    //     提交订单数据集合
    private List<CommitProductEntity> selectProductList(TextView tvGoodsCount) {
        CommitProductEntity commitProductEntity = new CommitProductEntity();
        commitProductEntity.setProductid(productId);
        commitProductEntity.setCount(Integer.parseInt(tvGoodsCount.getText().toString()));
        commitProductEntity.setExpressprice(productDetailEntity.getExpressprice());
        commitProductEntity.setDaijin(productDetailEntity.getMaxDaiJin());
        commitProductEntity.setJinbao(productDetailEntity.getMaxJinBao());
        if (productDetailEntity.getIsSpec() == 1) {
            if (selectSpecEntity != null) {
                commitProductEntity.setSpecid(selectSpecEntity.getId());
            } else {
                commitProductEntity.setSpecid(-1);
            }
        } else {
            commitProductEntity.setSpecid(-1);
        }
        if (productDetailEntity.getImgs() != null && productDetailEntity.getImgs().size() > 0) {
            commitProductEntity.setProductImg(productDetailEntity.getImgs().get(0).getUrl());
        }
        commitProductEntity.setProductName(productDetailEntity.getName());

        if (productDetailEntity.getIsSpec() == 1) {
            if (selectSpecEntity != null && selectSpecEntity.getId() != 0) {
                commitProductEntity.setProductPrice(selectSpecEntity.getPrice());
            }
        } else {
            if (productDetailEntity.getDiscountprice() != 0) {
                commitProductEntity.setProductPrice(productDetailEntity.getDiscountprice());
            } else {
                commitProductEntity.setProductPrice(productDetailEntity.getCostprice());
            }

        }

        commitProductEntity.setProductSpec(spec);


        List<CommitProductEntity> commitProductEntityList = new ArrayList<>();
        commitProductEntityList.add(commitProductEntity);
        return commitProductEntityList;
    }

    private void updateSelectTabs(TextView tv, TextView tvGoodsPrice, TextView tvPopChooseSpec, ImageView ivPopGoodsDetail,TextView kuCun) {
        ProductSpecEntity.ValueBean tag = (ProductSpecEntity.ValueBean) tv.getTag();
        if (!selectSpecValueListBean.contains(tag)) {
            for (int i = 0; i < selectSpecValueListBean.size(); i++) {
                if (selectSpecValueListBean.get(i).getMyId() == tag.getMyId()) {
                    selectSpecValueListBean.remove(i);
                    break;
                }
            }

            selectSpecValueListBean.add(tag);
        }
        int tagSpecId = tag.getId();
        int mId = tag.getMyId();
        for (int i = 0; i < tvTabs.size(); i++) {
            ProductSpecEntity.ValueBean tabsTag = (ProductSpecEntity.ValueBean) tvTabs.get(i).getTag();
            if (tabsTag.getMyId() == mId) {
                if (tabsTag.getId() == tagSpecId) {
                    tvTabs.get(i).setTextColor(getResources().getColor(R.color.appThemeColor));
                    tvTabs.get(i).setBackgroundResource(R.drawable.shape_app_theme_frame);
                } else {
                    tvTabs.get(i).setTextColor(getResources().getColor(R.color.appThemeSubTitleColor));
                    tvTabs.get(i).setBackgroundResource(R.drawable.shape_gray_frame);
                }
            }


        }
        Collections.sort(selectSpecValueListBean, new SortBySpecId());
        String sid = "";
        String selectText = "";
        for (int i = 0; i < selectSpecValueListBean.size(); i++) {
            sid += (TextUtils.isEmpty(sid) ? "" : ",") + selectSpecValueListBean.get(i).getId();
            MyLog.e("yang", "id==" + selectSpecValueListBean.get(i).getId() + ".....val==" + selectSpecValueListBean.get(i).getVal());
            selectText += (TextUtils.isEmpty(selectText) ? "" : ",") + selectSpecValueListBean.get(i).getVal();
        }
        spec = selectText;
        tvPopChooseSpec.setText("已选择" + spec);
        selectSpecApi(sid, tvGoodsPrice,ivPopGoodsDetail,kuCun);
    }

    class SortBySpecId implements Comparator<ProductSpecEntity.ValueBean> {
        @Override
        public int compare(ProductSpecEntity.ValueBean o1, ProductSpecEntity.ValueBean o2) {
            return o1.getId() - o2.getId();
        }
    }

    //    根据规格查询价格和库存
    private void selectSpecApi(String sid, final TextView tvGoodsPrice,final ImageView ivPopGoodsDetail,final TextView kuCun) {
        mMProgressDialog.show();
        HttpParams params = new HttpParams();
        params.put("iid", productId + "");
        params.put("sid", sid);

        EasyHttp.post(Constants.API_JSONAPI_SELECTSPEC)
                .params(params)
                .execute(new SimpleCallBack<String>() {
                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                        mMProgressDialog.dismiss();
                    }

                    @Override
                    public void onError(ApiException e) {
                        MyLog.d(TAG, "获取商品库存失败==" + e.toString());
                        MToast.makeTextShort(ProductDetailActivity.this, getString(R.string.service_error)).show();
                    }

                    @Override
                    public void onSuccess(String result) {
                        MyLog.e("yang", "商品库存==" + result);
                        int code = JsonUtil.getJsonValuesInt(result, "code");
                        String msg = JsonUtil.getJsonValuesString(result, "msg");
                        if (code == 0) {
                            Gson gson = new GsonBuilder().create();
                            selectSpecEntity = gson.fromJson(result, SelectSpecEntity.class);
                            tvGoodsPrice.setText("￥" + selectSpecEntity.getPrice());


                            if(selectSpecEntity.getCount()==-1){
                                kuCun.setText("库存: +9999");
                            }else {
                                kuCun.setText("库存: "+selectSpecEntity.getCount());
                            }

                            if (!TextUtils.isEmpty(selectSpecEntity.getImg())) {
                                ImageLoadUtil.displayImage(ProductDetailActivity.this, ivPopGoodsDetail,selectSpecEntity.getImg(), R.mipmap.app_logo, R.mipmap.app_logo);
                            }

                        } else {
                            selectSpecEntity = null;
                            tvGoodsPrice.setText("￥0.00");
                            MToast.makeTextShort(ProductDetailActivity.this, msg).show();
                        }

                    }
                });

    }

    //加入购物车接口
    private void setCarApi(String specid, String count) {
        mMProgressDialog.show();
        HttpParams params = new HttpParams();
        params.put("userid", UserHelper.getInstance().getloginEntity(ProductDetailActivity.this).getId() + "");
        params.put("productid", productId + "");
        params.put("specid", specid);
        params.put("count", count);
        MyLog.e("yang", "params==" + params.toString());
        EasyHttp.post(Constants.API_JSONAPI_SETCAR)
                .params(params)
                .execute(new SimpleCallBack<String>() {
                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                        mMProgressDialog.dismiss();
                    }

                    @Override
                    public void onError(ApiException e) {
                        MyLog.d(TAG, "加入购物车失败==" + e.toString());
                        MToast.makeTextShort(ProductDetailActivity.this, getString(R.string.service_error)).show();
                    }

                    @Override
                    public void onSuccess(String result) {
                        String data = PhoneUtils.checkResponseFlag(ProductDetailActivity.this, result, TAG);
                        if (data != null) {
                            MToast.makeTextShort(ProductDetailActivity.this, "加入购物车成功").show();
                            EventBus.getDefault().post(new InfoEnent(InfoEnent.ADD_CAR_SUCCESS));
                            popWnd.dismiss();
                        }
                    }
                });
    }

    private void myBack(){
        if (!MainActivity.isForeground) {
            finish();
            Intent i = new Intent(ProductDetailActivity.this, MainActivity.class);
            i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(i);
        }else {
            finish();
        }

    }
}
